import { defineStore } from 'pinia'
import { http } from '../utils/http'
import { ElMessage } from 'element-plus'

let lastMessageTime = 0;
const MESSAGE_THROTTLE = 1000; // 1秒内只允许显示一次消息

const showMessage = (message, type = 'success') => {
  const now = Date.now();
  if (now - lastMessageTime < MESSAGE_THROTTLE) {
    return; // 如果距离上次显示消息不足1秒，则不显示
  }
  
  // 更新上次显示消息的时间
  lastMessageTime = now;
  
  // 获取所有现有的消息
  const messages = document.querySelectorAll('.el-message');
  // 关闭所有现有的消息
  messages.forEach(msg => {
    msg.close && msg.close();
  });
  
  // 显示新消息
  ElMessage({
    message,
    type,
    duration: 2000
  });
};

export const usePetStore = defineStore('pet', {
  state: () => ({
    pet: null,
    lastHungerUpdateTime: null,
    updateTimer: null,
    statusLogs: [],
    accumulatedHungerDrop: 0,  // 新增：用于追踪累积的饥饿值降低
    lastEnergyUpdate: null
  }),
  persist: true,

  actions: {
    // 开始定期更新宠物状态
    startAutoUpdate() {
      if (this.updateTimer) {
        clearInterval(this.updateTimer);
      }
      
      // 重置累积值
      this.accumulatedHungerDrop = 0;
      this.lastEnergyUpdate = null;
      
      // 立即执行一次更新
      this.updatePetAutoStats();
      
      // 每10秒更新一次宠物状态
      this.updateTimer = setInterval(() => {
        this.updatePetAutoStats();
      }, 10000);
    },

    // 停止自动更新
    stopAutoUpdate() {
      if (this.updateTimer) {
        clearInterval(this.updateTimer);
        this.updateTimer = null;
      }
      // 重置累积值
      this.accumulatedHungerDrop = 0;
    },

    // 自动更新宠物状态
    async updatePetAutoStats() {
      if (this.pet) {
        console.log('Current pet stats:', {
          hunger: this.pet.hunger,
          happiness: this.pet.happiness,
          energy: this.pet.energy
        });
        
        const oldHunger = this.pet.hunger;
        const oldHappiness = this.pet.happiness;
        const oldEnergy = this.pet.energy;
        
        // 计算新的饥饿值
        let newHunger = Math.max(0, oldHunger - 5);  // 每10秒降低5%饥饿值
        const currentHungerDrop = oldHunger - newHunger;  // 本次饥饿值降低的百分比
        
        // 更新累积的饥饿值降低
        this.accumulatedHungerDrop += currentHungerDrop;
        
        // 计算心情值变化：当累积饥饿值降低达到10%或更多时，降低5%心情值
        let newHappiness = oldHappiness;
        if (this.accumulatedHungerDrop >= 10) {  // 如果累积饥饿值降低达到10%或更多
          newHappiness = Math.max(0, oldHappiness - 5);  // 降低5%心情值
          this.accumulatedHungerDrop = 0;  // 重置累积值
        }

        try {
          // 调用服务器端的自动恢复体力值接口
          if (oldEnergy < 100) {
            await http.post(`/pets/${this.pet.id}/recover-energy`);
          }

          // 更新其他状态
          const response = await http.put(`/pets/${this.pet.id}`, {
            hunger: newHunger,
            happiness: newHappiness
          });
          
          if (response && response.pet) {
            console.log('Updated pet stats:', {
              hunger: response.pet.hunger,
              happiness: response.pet.happiness,
              energy: response.pet.energy
            });
            this.pet = response.pet;
          }

          // 添加状态日志
          const logContent = [];
          
          // 饥饿值变化日志
          if (currentHungerDrop > 0) {
            logContent.push(`宠物饥饿值降低了${currentHungerDrop}%`);
            if (oldHappiness !== newHappiness) {
              logContent.push(`心情值降低了5%`);
            }
          }
          
          // 体力值变化日志
          if (this.pet.energy > oldEnergy) {
            logContent.push(`体力值恢复了${this.pet.energy - oldEnergy}%`);
          }
          
          // 如果有任何状态变化，添加日志
          if (logContent.length > 0) {
            this.addStatusLog({
              id: Date.now(),
              content: logContent.join('，'),
              type: currentHungerDrop > 0 ? 'warning' : 'success',
              time: new Date().toLocaleTimeString()
            });
          }
        } catch (error) {
          console.error('Failed to update pet stats:', error);
        }
      }
    },

    // 添加状态日志
    addStatusLog(log) {
      this.statusLogs.unshift(log);
      // 保持最多50条日志
      if (this.statusLogs.length > 50) {
        this.statusLogs.pop();
      }
    },

    // 更新宠物状态
    async updatePetStats(stats) {
      try {
        const response = await http.put(`/pets/${this.pet.id}`, stats)
        if (response && response.pet) {
          this.pet = response.pet
        }
      } catch (error) {
        console.error('Failed to update pet stats:', error)
      }
    },

    async fetchPet() {
      try {
        const response = await http.get('/pets/my-pet')
        if (response && response.pet) {
          this.pet = response.pet
        }
      } catch (error) {
        if (
          error?.response?.status === 404 &&
          error?.response?.data?.message === '未找到宠物'
        ) {
          this.clearPet()  // 确保清除本地状态
          return
        }
        console.error('获取宠物信息失败:', error)
      }
    },

    async createPet(name, species, appearance, personality, introduction) {
      try {
        const response = await http.post('/pets', {
          name,
          species,
          appearance,
          personality,
          introduction
        })
        if (response && response.pet) {
          this.pet = response.pet
          this.startAutoUpdate()  // 启动自动更新
          ElMessage.success('创建宠物成功')
        }
      } catch (error) {
        ElMessage.error('创建宠物失败')
        throw error
      }
    },

    async updatePet(data) {
      try {
        const response = await http.put(`/pets/${this.pet.id}`, data)
        const petResponse = response.data
        if (petResponse.pet) {
          this.pet = petResponse.pet
          ElMessage.success('更新宠物成功')
        }
      } catch (error) {
        ElMessage.error('更新宠物失败')
        throw error
      }
    },

    async feedPet() {
      try {
        if (this.pet.hunger >= 100) {
          showMessage('宠物已经饱了', 'warning');
          return;
        }
        
        // 更新宠物状态 - 只增加饥饿值和心情值
        const newStats = {
          hunger: Math.min(100, this.pet.hunger + 5),
          happiness: Math.min(100, this.pet.happiness + 2)
        }
        
        await this.updatePetStats(newStats);
        showMessage('喂食成功');
      } catch (error) {
        showMessage('喂食失败', 'error');
        throw error;
      }
    },

    // 获取候选宠物
    async fetchPetCandidates() {
      try {
        const response = await http.get('/pets/candidates');
        if (response && response.candidates) {
          return response.candidates;
        }
        return [];
      } catch (error) {
        ElMessage.error('获取候选宠物失败');
        return [];
      }
    },

    // 清空当前宠物
    clearPet() {
      this.stopAutoUpdate();  // 停止自动更新
      this.pet = null;
      // 清除pinia持久化存储
      if (localStorage.getItem('pinia')) {
        try {
          const piniaData = JSON.parse(localStorage.getItem('pinia'))
          if (piniaData && piniaData.pet) {
            delete piniaData.pet
            localStorage.setItem('pinia', JSON.stringify(piniaData))
          }
        } catch (e) {}
      }
    },

    // 弃养宠物
    async abandonPet(petId) {
      try {
        await http.delete(`/pets/${petId}`)
        this.clearPet()
        ElMessage.success('已成功弃养宠物')
      } catch (error) {
        ElMessage.error('弃养宠物失败')
        throw error
      }
    },

    async trainPet() {
      try {
        if (!this.pet) {
          ElMessage.error('没有找到宠物');
          return;
        }

        // 只检查体力和饥饿值要求
        if (this.pet.energy < 10) {
          ElMessage.warning('体力不足，无法训练');
          return;
        }

        if (this.pet.hunger < 5) {
          ElMessage.warning('饥饿值太低，需要先喂食');
          return;
        }

        // 保存旧的状态值用于比较
        const oldEnergy = this.pet.energy;
        const oldHappiness = this.pet.happiness;
        const oldExperience = this.pet.experience;

        const response = await http.post(`/pets/${this.pet.id}/train`);
        if (response.data.status === 'success' && response.data.data.pet) {
          // 更新宠物状态
          this.pet = response.data.data.pet;
          
          // 计算状态变化
          const energyChange = oldEnergy - this.pet.energy;
          const happinessChange = this.pet.happiness - oldHappiness;
          const experienceChange = this.pet.experience - oldExperience;
          
          // 更新训练日志，显示详细的训练效果
          const logContent = [
            '训练完成！',
            `消耗体力值${energyChange}%`,
            `心情值${happinessChange >= 0 ? '提升' : '降低'}${Math.abs(happinessChange)}%`,
            `获得经验值${experienceChange}点`
          ].join('，');
          
          this.addStatusLog({
            id: Date.now(),
            content: logContent,
            type: 'success',
            time: new Date().toLocaleTimeString()
          });
          
          ElMessage.success('训练成功！');
        }
      } catch (error) {
        console.error('Train pet error:', error);
        ElMessage.error(error.response?.data?.message || '训练失败');
        throw error;
      }
    }
  }
})
